﻿namespace Snipps.Infrastructure.Behaviors
{
    using System.Windows;
    using System.Windows.Interactivity;

    public class BindableFocusBehavior : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty FocusPropertyProperty = DependencyProperty.Register(
            "FocusProperty", 
            typeof(bool), 
            typeof(BindableFocusBehavior), 
            new PropertyMetadata(default(bool), OnFocusPropertyChanged));

        public bool FocusProperty
        {
            get
            {
                return (bool)GetValue(FocusPropertyProperty);
            }

            set
            {
                SetValue(FocusPropertyProperty, value);
            }
        }

        private static void OnFocusPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var beh = d as BindableFocusBehavior;
            if (beh != null)
            {
                if ((bool)e.NewValue)
                {
                    beh.FocusAssoctiatedObject();
                }
            }
        }

        public void FocusAssoctiatedObject()
        {
            var element = AssociatedObject;
            if (element != null)
            {
                element.Focus();
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            if (FocusProperty)
            {
                FocusAssoctiatedObject();
            }

            AssociatedObject.GotFocus += AssociatedObject_GotFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
        }

        private void AssociatedObject_GotFocus(object sender, RoutedEventArgs routedEventArgs)
        {
            FocusProperty = true;
        }
    }
}